<template>
  <div class="dashboard-container">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="header-left">
      <h1 class="title">高校竞赛平台数据大屏</h1>
        <div class="subtitle">University Competition Platform Dashboard</div>
      </div>
      <div class="header-right">
        <div class="time-info">
          <div class="current-time">{{ currentTime }}</div>
          <div class="date">{{ currentDate }}</div>
        </div>
        <div class="weather-info" @click="showWeatherDialog = true">
          <i :class="weatherInfo.icon"></i>
          <span>{{ weatherInfo.temperature }}°C</span>
          <span class="weather-location">{{ weatherInfo.location }}</span>
          <span class="weather-status" :title="weatherInfo.apiSource || '实时天气'">
            <i class="el-icon-refresh"></i>
          </span>
        </div>
      </div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <!-- 竞赛统计饼图 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>竞赛类型分布</h3>
            <div class="chart-legend">
              <span class="legend-item" v-for="item in competitionTypeData" :key="item.name">
                <span class="legend-color" :style="{backgroundColor: item.color}"></span>
                {{ item.name }}: {{ item.value }}
              </span>
            </div>
          </div>
          <div ref="competitionPieChart" class="chart-container"></div>
        </div>

        <!-- 赛制统计 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>赛制分布</h3>
          </div>
          <div ref="competitionRulesChart" class="chart-container"></div>
        </div>
      </div>

      <!-- 中间面板 -->
      <div class="center-panel">
        <!-- 通知公告滚动 -->
        <div class="notice-card">
          <div class="card-header">
            <h3>最新通知公告</h3>
            <el-button type="text" @click="refreshNotices">刷新</el-button>
          </div>
          <div class="notice-list">
            <div 
              v-for="notice in noticeList" 
              :key="notice.noticeId" 
              class="notice-item"
              @click="viewNotice(notice)"
            >
              <div class="notice-title">{{ notice.noticeTitle }}</div>
              <div class="notice-meta">
                <span class="notice-type">{{ getNoticeTypeName(notice.noticeType) }}</span>
                <span class="notice-time">{{ formatTime(notice.createTime) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 实时数据统计 -->
        <div class="stats-card">
          <div class="card-header">
            <h3>实时数据统计</h3>
          </div>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value">{{ totalCompetitions }}</div>
              <div class="stat-label">竞赛总数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ totalUniversities }}</div>
              <div class="stat-label">参与高校</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ totalRegions }}</div>
              <div class="stat-label">覆盖地区</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ totalPrizes }}</div>
              <div class="stat-label">奖项设置</div>
            </div>
          </div>
        </div>

        <!-- 竞赛状态统计 -->
        <div class="stats-card">
          <div class="card-header">
            <h3>竞赛状态分布</h3>
          </div>
          <div class="status-stats">
            <div class="status-item" v-for="status in competitionStatusStats" :key="status.status">
              <div class="status-info">
                <div class="status-label">{{ getStatusText(status.status) }}</div>
                <div class="status-value">{{ status.count }}</div>
              </div>
              <div class="status-bar">
                <div 
                  class="status-progress" 
                  :style="{
                    width: `${(status.count / totalCompetitions * 100).toFixed(1)}%`,
                    backgroundColor: getStatusColor(status.status)
                  }"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧面板 -->
      <div class="right-panel">
        <!-- 参赛高校学生区域分布 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>参赛高校学生区域分布</h3>
            <div class="chart-legend">
              <span class="legend-item" v-for="item in studentRegionData" :key="item.name">
                <span class="legend-color" :style="{backgroundColor: item.color}"></span>
                {{ item.name }}: {{ item.value }}
              </span>
            </div>
          </div>
          <div ref="studentRegionChart" class="chart-container"></div>
        </div>

        <!-- 竞赛时间轴 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3>竞赛时间分布</h3>
          </div>
          <div ref="competitionTimelineChart" class="chart-container"></div>
        </div>
      </div>
    </div>
    
    <!-- 底部地图 -->
    <div class="bottom-panel">
      <div class="chart-card">
        <div class="chart-header">
          <h3>全国竞赛分布地图</h3>
        </div>
        <div ref="chinaMapChart" class="map-container"></div>
      </div>
    </div>

    <!-- 天气设置对话框 -->
    <el-dialog v-model="showWeatherDialog" title="天气设置" width="500px" :close-on-click-modal="false">
      <el-form :model="weatherForm" label-width="80px">
        <el-form-item label="选择地区">
          <el-cascader
            v-model="weatherForm.region"
            :options="regionOptions"
            :props="cascaderProps"
            placeholder="请选择地区"
            style="width: 100%"
            @change="handleRegionChange"
          />
        </el-form-item>
        <el-form-item label="当前地区">
          <el-input v-model="weatherForm.currentLocation" readonly />
        </el-form-item>
        <el-form-item label="天气信息">
          <div class="weather-preview" v-loading="weatherLoading">
            <div class="weather-icon">
              <i :class="weatherInfo.icon"></i>
            </div>
            <div class="weather-details">
              <div class="weather-temp">{{ weatherInfo.temperature }}°C</div>
              <div class="weather-desc">{{ weatherInfo.description }}</div>
              <div class="weather-wind">风力: {{ weatherInfo.wind }}</div>
              <div class="weather-humidity">湿度: {{ weatherInfo.humidity }}%</div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showWeatherDialog = false">取消</el-button>
        <el-button type="primary" @click="updateWeather" :loading="weatherLoading">更新天气</el-button>
      </template>
    </el-dialog>

    <!-- 公告预览对话框 -->
    <el-dialog v-model="showNoticeDialog" title="公告预览" width="800px" :close-on-click-modal="false">
      <div class="notice-preview">
        <div class="notice-header">
          <h2>{{ currentNotice.noticeTitle }}</h2>
          <div class="notice-meta">
            <span class="notice-type">{{ getNoticeTypeName(currentNotice.noticeType) }}</span>
            <span class="notice-time">{{ formatTime(currentNotice.createTime) }}</span>
            <span class="notice-author">发布人: {{ currentNotice.createBy }}</span>
          </div>
        </div>
        <div class="notice-content" v-html="currentNotice.noticeContent"></div>
      </div>
      <template #footer>
        <el-button @click="showNoticeDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, getCurrentInstance } from 'vue'
import * as echarts from 'echarts'
import chinaMap from '@/api/china.json'
import { listNotice } from '@/api/system/notice'
import { getStatistics, getCompetitionTypeDistribution, getUniversityRegionDistribution, getCompetitionTimeDistribution, getNationalCompetitionDistribution, getCompetitionStatusCount, getStudentRegionDistribution } from '@/api/race/dashboard'
import { getWeatherInfo } from '@/api/weather'

const { proxy } = getCurrentInstance()

// 响应式数据
const currentTime = ref('')
const currentDate = ref('')
const noticeList = ref([])
const totalCompetitions = ref(0)
const totalUniversities = ref(0)
const totalRegions = ref(0)
const totalPrizes = ref(0)
const competitionStatusStats = ref([])

// 天气相关数据
const weatherInfo = ref({
  temperature: '22',
  location: '北京市',
  description: '晴',
  wind: '微风',
  humidity: '45',
  icon: 'el-icon-sunny',
  apiSource: '实时天气'
})

const showWeatherDialog = ref(false)
const weatherLoading = ref(false)
const weatherForm = ref({
  region: [],
  currentLocation: '北京市'
})

// 公告相关数据
const showNoticeDialog = ref(false)
const currentNotice = ref({})

// 地区选项
const regionOptions = ref([])
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  emitPath: false,
  checkStrictly: false
}

// 图表数据
const competitionTypeData = ref([
  { name: '本科组', value: 45, color: '#5470c6' },
  { name: '专科组', value: 30, color: '#91cc75' },
  { name: '研究生组', value: 25, color: '#fac858' }
])

const studentRegionData = ref([])

// 定时器
let timeInterval = null
let dataInterval = null

// 图表引用
const competitionPieChart = ref()
const competitionRulesChart = ref()
const universityRegionChart = ref()
const competitionTimelineChart = ref()
const chinaMapChart = ref()
const studentRegionChart = ref()

// 图表实例
let competitionPieChartInstance = null
let competitionRulesChartInstance = null
let universityRegionChartInstance = null
let competitionTimelineChartInstance = null
let chinaMapChartInstance = null
let studentRegionChartInstance = null

// 更新时间
function updateTime() {
      const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
    second: '2-digit'
  })
  currentDate.value = now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
}

// 获取通知公告
async function loadNotices() {
  try {
    const response = await listNotice({ pageNum: 1, pageSize: 5, status: '0' })
    noticeList.value = response.rows || []
  } catch (error) {
    console.error('获取通知公告失败:', error)
  }
}

// 获取统计数据
async function loadStatistics() {
  try {
    const response = await getStatistics()
    if (response.data) {
      totalCompetitions.value = response.data.totalCompetitions || 0
      totalUniversities.value = response.data.totalUniversities || 0
      totalRegions.value = response.data.totalRegions || 0
      totalPrizes.value = response.data.totalPrizes || 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
  
  // 加载竞赛状态统计
  loadCompetitionStatusStats()
}

// 加载竞赛状态统计
async function loadCompetitionStatusStats() {
  try {
    const response = await getCompetitionStatusCount()
    if (response.code === 200) {
      competitionStatusStats.value = response.data || []
    }
  } catch (error) {
    console.error('加载竞赛状态统计失败:', error)
    competitionStatusStats.value = []
  }
}

// 加载参赛高校学生区域分布数据
async function loadStudentRegionData() {
  try {
    const response = await getStudentRegionDistribution()
    if (response.code === 200 && response.data) {
      studentRegionData.value = response.data.data || []
      // 更新图表
      if (studentRegionChartInstance) {
        updateStudentRegionChart()
      }
    }
  } catch (error) {
    console.error('加载参赛高校学生区域分布数据失败:', error)
    studentRegionData.value = []
  }
}

// 获取通知类型名称
function getNoticeTypeName(type) {
  const typeMap = {
    '1': '通知',
    '2': '公告'
  }
  return typeMap[type] || '未知'
}

// 格式化时间
function formatTime(time) {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
}

// 查看通知详情
function viewNotice(notice) {
  currentNotice.value = notice
  showNoticeDialog.value = true
}

// 刷新通知
function refreshNotices() {
  loadNotices()
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    1: '可报名',
    2: '截止报名',
    3: '竞赛中',
    4: '已完赛'
  }
  return statusMap[status] || '未知'
}

// 获取状态颜色
function getStatusColor(status) {
  const colorMap = {
    1: '#67C23A',  // 可报名 - 绿色
    2: '#E6A23C',  // 截止报名 - 橙色
    3: '#409EFF',  // 竞赛中 - 蓝色
    4: '#909399'   // 已完赛 - 灰色
  }
  return colorMap[status] || '#909399'
}

// 天气相关方法
async function loadRegionOptions() {
  try {
    // 优先使用全国地区数据
    const chinaRegions = await import('@/api/china-regions.json')
    regionOptions.value = buildRegionTreeFromChinaData(chinaRegions.default)
  } catch (error) {
    console.error('加载全国地区数据失败，尝试数据库数据:', error)
    try {
      const response = await fetch('/dev-api/race/region/list?pageNum=1&pageSize=10000')
      const data = await response.json()
      if (data.rows) {
        regionOptions.value = buildRegionTree(data.rows)
      } else {
        regionOptions.value = getBackupRegionData()
      }
    } catch (dbError) {
      console.error('加载数据库地区数据失败:', dbError)
      regionOptions.value = getBackupRegionData()
    }
  }
}

function buildRegionTreeFromChinaData(chinaData) {
  const result = []
  
  for (const [provinceName, provinceData] of Object.entries(chinaData)) {
    const province = {
      value: provinceName,
      label: provinceName,
      children: []
    }
    
    if (provinceData.children) {
      for (const [cityName, cityData] of Object.entries(provinceData.children)) {
        const city = {
          value: cityName,
          label: cityName,
          children: []
        }
        
        if (cityData.children) {
          for (const [districtName, districtData] of Object.entries(cityData.children)) {
            city.children.push({
              value: districtName,
              label: districtName
            })
          }
        }
        
        province.children.push(city)
      }
    }
    
    result.push(province)
  }
  
  return result
}

function buildRegionTree(regions) {
  const tree = {}
  
  regions.forEach(region => {
    if (!tree[region.province]) {
      tree[region.province] = {
        value: region.province,
        label: region.province,
        children: []
      }
    }
    
    if (region.city && !tree[region.province].children.find(c => c.value === region.city)) {
      tree[region.province].children.push({
        value: region.city,
        label: region.city
      })
    }
  })
  
  return Object.values(tree)
}

function getBackupRegionData() {
  return [
    {
      value: '北京市',
      label: '北京市',
      children: [
        { value: '北京市', label: '北京市' }
      ]
    },
    {
      value: '上海市',
      label: '上海市',
      children: [
        { value: '上海市', label: '上海市' }
      ]
    },
    {
      value: '广东省',
      label: '广东省',
      children: [
        { value: '广州市', label: '广州市' },
        { value: '深圳市', label: '深圳市' },
        { value: '珠海市', label: '珠海市' }
      ]
    },
    {
      value: '江苏省',
      label: '江苏省',
      children: [
        { value: '南京市', label: '南京市' },
        { value: '苏州市', label: '苏州市' },
        { value: '无锡市', label: '无锡市' }
      ]
    },
    {
      value: '浙江省',
      label: '浙江省',
      children: [
        { value: '杭州市', label: '杭州市' },
        { value: '宁波市', label: '宁波市' },
        { value: '温州市', label: '温州市' }
      ]
    }
  ]
}

function handleRegionChange(value) {
  if (value) {
    weatherForm.value.currentLocation = value
    // 自动更新天气信息
    updateWeatherForRegion(value)
  }
}

// 自动更新天气信息
async function updateWeatherForRegion(location) {
  try {
    const weatherData = await getWeatherInfo(location)
    weatherInfo.value = weatherData
    console.log('自动更新天气信息:', weatherData)
  } catch (error) {
    console.error('自动更新天气失败:', error)
  }
}

async function updateWeather() {
  weatherLoading.value = true
  try {
    const location = weatherForm.value.currentLocation
    // 使用天气API服务
    const weatherData = await getWeatherInfo(location)
    weatherInfo.value = weatherData
    showWeatherDialog.value = false
    proxy.$modal.msgSuccess('天气信息更新成功')
  } catch (error) {
    console.error('获取天气信息失败:', error)
    proxy.$modal.msgError('获取天气信息失败')
  } finally {
    weatherLoading.value = false
  }
}


// 初始化竞赛类型饼图
async function initCompetitionPieChart() {
  competitionPieChartInstance = echarts.init(competitionPieChart.value)
  
  try {
    const response = await getCompetitionTypeDistribution()
    const data = response.data?.data || competitionTypeData.value
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: '#fff'
        }
      },
      series: [
        {
          name: '竞赛类型',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['60%', '50%'],
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    competitionPieChartInstance.setOption(option)
  } catch (error) {
    console.error('初始化竞赛类型饼图失败:', error)
  }
}

// 初始化赛制分布图
function initCompetitionRulesChart() {
  competitionRulesChartInstance = echarts.init(competitionRulesChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['团队赛', '个人赛'],
      axisLabel: {
        color: '#fff'
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#fff'
      }
    },
    series: [
      {
        data: [65, 35],
        type: 'bar',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  competitionRulesChartInstance.setOption(option)
}

// 初始化高校地区分布图
async function initUniversityRegionChart() {
  universityRegionChartInstance = echarts.init(universityRegionChart.value)
  
  try {
    const response = await getUniversityRegionDistribution()
    const data = response.data?.data || [
      { value: 35, name: '北京' },
      { value: 28, name: '上海' },
      { value: 22, name: '广东' },
      { value: 15, name: '江苏' },
      { value: 12, name: '浙江' },
      { value: 8, name: '其他' }
    ]
    
    const option = {
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          name: '高校分布',
          type: 'pie',
          radius: '60%',
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    universityRegionChartInstance.setOption(option)
  } catch (error) {
    console.error('初始化高校地区分布图失败:', error)
  }
}

// 初始化竞赛时间轴
async function initCompetitionTimelineChart() {
  competitionTimelineChartInstance = echarts.init(competitionTimelineChart.value)
  
  try {
    const response = await getCompetitionTimeDistribution()
    const months = response.data?.months || ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    const values = response.data?.values || [2, 3, 5, 8, 12, 15, 18, 16, 14, 10, 6, 4]
    
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: months,
        axisLabel: {
          color: '#fff'
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#fff'
        }
      },
      series: [
        {
          data: values,
          type: 'line',
          smooth: true,
          lineStyle: {
            color: '#5470c6',
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
              { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
            ])
          }
        }
      ]
    }
    competitionTimelineChartInstance.setOption(option)
  } catch (error) {
    console.error('初始化竞赛时间轴失败:', error)
  }
}

// 初始化中国地图
async function initChinaMapChart() {
  echarts.registerMap('china', chinaMap)
  chinaMapChartInstance = echarts.init(chinaMapChart.value)
  
  try {
    const response = await getNationalCompetitionDistribution()
    const data = response.data?.data || [
      { name: '北京', value: 35 },
      { name: '上海', value: 28 },
      { name: '广东', value: 22 },
      { name: '江苏', value: 15 },
      { name: '浙江', value: 12 },
      { name: '山东', value: 8 },
      { name: '四川', value: 6 },
      { name: '湖北', value: 5 },
      { name: '湖南', value: 4 },
      { name: '河南', value: 3 }
    ]
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}<br/>竞赛数量: {c}'
      },
      visualMap: {
        min: 0,
        max: 100,
        left: 'left',
        top: 'bottom',
        text: ['高', '低'],
        textStyle: {
          color: '#fff'
        },
        inRange: {
          color: ['#50a3ba', '#eac736', '#d94e5d']
        }
      },
        geo: {
        map: 'china',
        roam: false,
        label: {
          emphasis: {
            show: false
          }
        },
        itemStyle: {
          normal: {
            areaColor: '#323c48',
            borderColor: '#111'
          },
          emphasis: {
            areaColor: '#2a333d'
          }
        }
      },
      series: [
        {
          name: '竞赛分布',
          type: 'map',
          map: 'china',
          geoIndex: 0,
          data: data
        }
      ]
    }
    chinaMapChartInstance.setOption(option)
  } catch (error) {
    console.error('初始化中国地图失败:', error)
  }
}

// 初始化参赛高校学生区域分布图表
async function initStudentRegionChart() {
  studentRegionChartInstance = echarts.init(studentRegionChart.value)
  
  try {
    const response = await getStudentRegionDistribution()
    const data = response.data?.data || []
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#333',
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        show: false
      },
      series: [
        {
          name: '参赛学生分布',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold',
              color: '#fff'
            },
            itemStyle: {
              shadowBlur: 20,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          labelLine: {
            show: false
          },
          data: data.map(item => ({
            value: item.value,
            name: item.name,
            itemStyle: {
              color: item.color || '#3ba272'  // 添加默认颜色
            }
          }))
        }
      ]
    }
    
    studentRegionChartInstance.setOption(option)
  } catch (error) {
    console.error('初始化参赛高校学生区域分布图表失败:', error)
  }
}

// 更新参赛高校学生区域分布图表
function updateStudentRegionChart() {
  if (!studentRegionChartInstance || !studentRegionData.value.length) return
  
  const option = {
    series: [{
      data: studentRegionData.value.map(item => ({
        value: item.value,
        name: item.name,
        itemStyle: {
          color: item.color || '#3ba272'  // 添加默认颜色
        }
      }))
    }]
  }
  
  studentRegionChartInstance.setOption(option)
}

// 初始化所有图表
function initCharts() {
  initCompetitionPieChart()
  initCompetitionRulesChart()
  initUniversityRegionChart()
  initCompetitionTimelineChart()
  initChinaMapChart()
  initStudentRegionChart()
}

// 窗口大小改变时重新调整图表
function handleResize() {
  if (competitionPieChartInstance) competitionPieChartInstance.resize()
  if (competitionRulesChartInstance) competitionRulesChartInstance.resize()
  if (universityRegionChartInstance) universityRegionChartInstance.resize()
  if (competitionTimelineChartInstance) competitionTimelineChartInstance.resize()
  if (chinaMapChartInstance) chinaMapChartInstance.resize()
  if (studentRegionChartInstance) studentRegionChartInstance.resize()
}

// 组件挂载
onMounted(() => {
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
  
  // 加载数据
  loadNotices()
  loadStatistics()
  loadRegionOptions()
  loadStudentRegionData()
  
  // 初始化图表
  setTimeout(() => {
    initCharts()
  }, 100)
  
  // 定时刷新数据
  dataInterval = setInterval(() => {
    loadNotices()
    loadStatistics()
    loadStudentRegionData()
  }, 30000) // 30秒刷新一次
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(() => {
  if (timeInterval) clearInterval(timeInterval)
  if (dataInterval) clearInterval(dataInterval)
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (competitionPieChartInstance) competitionPieChartInstance.dispose()
  if (competitionRulesChartInstance) competitionRulesChartInstance.dispose()
  if (universityRegionChartInstance) universityRegionChartInstance.dispose()
  if (competitionTimelineChartInstance) competitionTimelineChartInstance.dispose()
  if (chinaMapChartInstance) chinaMapChartInstance.dispose()
})
</script>

<style scoped>
.dashboard-container {
  height: 100vh;
  background-image: url('/img1945086329578639362/login-bg.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  color: #fff;
  padding: 20px;
  overflow: hidden;
  position: relative;
}

.dashboard-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 1;
}

.dashboard-container > * {
  position: relative;
  z-index: 2;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 15px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
}

.header:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
}

.header-left .title {
  font-size: 32px;
  margin: 0 0 5px 0;
  font-weight: bold;
}

.header-left .subtitle {
  font-size: 14px;
  opacity: 0.8;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 30px;
}

.time-info {
  text-align: right;
}

.current-time {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.date {
  font-size: 14px;
  opacity: 0.8;
}

.weather-info {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 20px;
  height: calc(100vh - 140px);
  margin-bottom: 20px;
}

.left-panel,
.right-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.center-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-card {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 15px;
  padding: 20px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  flex: 1;
  min-height: 300px;
  transition: all 0.3s ease;
}

.chart-card:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.chart-container {
  height: calc(100% - 50px);
  width: 100%;
}

.notice-card {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 15px;
  padding: 20px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  flex: 1;
  transition: all 0.3s ease;
}

.notice-card:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.notice-list {
  max-height: 300px;
  overflow-y: auto;
}

.notice-item {
  padding: 15px;
  margin-bottom: 10px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.notice-item:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: translateX(5px);
}

.notice-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #fff;
}

.notice-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  opacity: 0.7;
}

.notice-type {
  background: rgba(84, 112, 198, 0.3);
  padding: 2px 8px;
  border-radius: 12px;
}

.stats-card {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 15px;
  padding: 20px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  flex: 1;
  transition: all 0.3s ease;
}

.stats-card:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #5470c6;
}

.stat-label {
  font-size: 14px;
  opacity: 0.8;
}

/* 状态统计样式 */
.status-stats {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.status-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.status-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-label {
  font-size: 14px;
  font-weight: 500;
}

.status-value {
  font-size: 18px;
  font-weight: bold;
  color: #5470c6;
}

.status-bar {
  width: 100%;
  height: 6px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
  overflow: hidden;
}

.status-progress {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s ease;
}

.bottom-panel {
  height: 300px;
}

.map-container {
  height: 250px;
  width: 100%;
}

.chart-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  gap: 5px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

/* 滚动条样式 */
.notice-list::-webkit-scrollbar {
  width: 6px;
}

.notice-list::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.notice-list::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.notice-list::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 天气相关样式 */
.weather-info {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.weather-info:hover {
  background: rgba(255, 255, 255, 0.1);
}

.weather-location {
  font-size: 12px;
  opacity: 0.8;
}

.weather-status {
  font-size: 12px;
  opacity: 0.6;
  margin-left: 5px;
  cursor: help;
}

.weather-status:hover {
  opacity: 1;
}

.weather-preview {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
}

.weather-icon {
  font-size: 32px;
  color: #5470c6;
}

.weather-details {
  flex: 1;
}

.weather-temp {
  font-size: 24px;
  font-weight: bold;
  color: #5470c6;
  margin-bottom: 5px;
}

.weather-desc {
  font-size: 14px;
  margin-bottom: 3px;
}

.weather-wind,
.weather-humidity {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 2px;
}

/* 公告预览样式 */
.notice-preview {
  max-height: 600px;
  overflow-y: auto;
  background: #1a1a1a;
  padding: 20px;
  border-radius: 8px;
}

.notice-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.notice-header h2 {
  margin: 0 0 10px 0;
  color: #fff;
  font-size: 20px;
}

.notice-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  opacity: 0.8;
}

.notice-meta span {
  padding: 2px 8px;
  background: rgba(84, 112, 198, 0.3);
  border-radius: 12px;
  color: #fff;
}

.notice-content {
  color: #fff !important;
  line-height: 1.6;
  background: transparent;
}

.notice-content * {
  color: #fff !important;
}

.notice-content h1,
.notice-content h2,
.notice-content h3,
.notice-content h4,
.notice-content h5,
.notice-content h6 {
  color: #5470c6 !important;
  margin: 15px 0 10px 0;
}

.notice-content p {
  margin: 10px 0;
  color: #fff !important;
}

.notice-content ul,
.notice-content ol {
  margin: 10px 0;
  padding-left: 20px;
}

.notice-content li {
  margin: 5px 0;
  color: #fff !important;
}

.notice-content strong,
.notice-content b {
  color: #5470c6 !important;
  font-weight: bold;
}

.notice-content em,
.notice-content i {
  color: #ccc !important;
  font-style: italic;
}

.notice-content a {
  color: #5470c6 !important;
  text-decoration: underline;
}

.notice-content blockquote {
  border-left: 4px solid #5470c6;
  padding-left: 15px;
  margin: 15px 0;
  background: rgba(84, 112, 198, 0.1);
  padding: 10px 15px;
  border-radius: 4px;
}

.notice-content code {
  background: rgba(84, 112, 198, 0.2);
  padding: 2px 6px;
  border-radius: 3px;
  color: #5470c6 !important;
  font-family: 'Courier New', monospace;
}

.notice-content pre {
  background: rgba(0, 0, 0, 0.3);
  padding: 15px;
  border-radius: 6px;
  overflow-x: auto;
  border: 1px solid rgba(84, 112, 198, 0.3);
}

.notice-content pre code {
  background: transparent;
  padding: 0;
  color: #fff !important;
}
</style>